'use strict';

import React, {Component, PropTypes} from 'react';
import ReactDOM, {render} from 'react-dom';
import {R_header_fixed} from './common/index';
import {HttpService, Toast} from '../Http';

//import { Link} from 'react-router';
import Link from './common/Link'

import imgCard from '../img/card.png'
import phone from '../img/more/phone.png'
import deletes from '../img/more/delete.png'
import shiming from '../img/more/shiming.png'
import pay from '../img/pay/pay.png'
import genghuan from '../img/genghuan.png'
import scode from '../img/scode.png'
import scodeh from '../img/scode2.png'
import users from '../img/users.png'
import authen from '../img/more/authen.png'
import unauthen from '../img/more/unauthen.png'
import firewall from '../img/firewall.png'
import disturb from '../img/disturb.png'
import j from '../img/more/jiantou.png'
import order from '../img/order.png'
import header from '../img/login/header.jpg'
import footer from '../img/login/footer.jpg'
import Popup from './common/popup'


export default class More extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);

        this.state = {
            info: {},
            admin: {},
            uimg: users,
            utel: localStorage.userphone,
            viewCode: 0,
            viewtime: 0,
            firewallSwitch: localStorage.firewallSwitch
        };

        this.config = {
            isSure: false,
            isCancel: false,
            no: '取消',
            yes: '确定',
            yes_cb: () => {
                if (this.config.type == 'change') {
                    console.log('更换设备');
                    //_hmt.push(['_trackEvent', 'page', 'more', '更换设备']);
                    this.context.router.push('/addDevice/change');
                    return;
                }
                console.log('解绑设备');
                //_hmt.push(['_trackEvent', 'page', 'more', '解绑设备']);
                if (!!this.state.info.isadmin) {
                    this.delDevice2()
                } else {
                    this.delDevice()
                }
            },
            no_cb: () => {
                this.setState({
                    admin: {
                        flag: false
                    }
                });
            }
        };
    }

    /**
     * 点击升级设备
     */

    /**
     * map页面加载完后--加载百度统计点击事件
     * 缴费的统计事件在componentWillMount方法里面
     * 升级设备统计事件在shengJi()方法里面
     */
    componentDidMount(){
        //遍历页面按钮--添加百度统计点击事件
        // document.querySelector('.adddevicelink').onclick=function(){
        //     console.log('添加设备');
        //     _hmt.push(['_trackEvent', 'page', 'more', '添加设备']);
        // }
        // document.querySelector('.buydevicelink').onclick=function(){
        //     console.log('购买设备');
        //     _hmt.push(['_trackEvent', 'page', 'more', '购买设备']);
        // }
    }

    componentWillMount() {
        if (localStorage.appToken == undefined) {
            Toast.toast('请先登录！');
            this.context.router.push('/');
            return;
        }
        HttpService.query({
            url: '/app/user/getUserinfo',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10116) {
                    let uimg = this.state.uimg;
                    if (res.data.headimg)
                        uimg = '/media' + res.data.headimg
                    this.setState({utel: res.data.telephone, uimg})
                    localStorage.userphone = res.data.telephone
                }
            })
        });
        HttpService.query({
            url: '/app/object/getBabyJxt',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10038') {
                    let viewtime = 0;
                    if (res.data.deviceType == 2) {
                        if (localStorage.overtime == undefined) {
                            if ((new Date().getTime() - new Date(res.data.endtime).getTime()) / 24 / 60 / 60 / 1000 >= -30)
                                viewtime = 1
                        } else {
                            if (localStorage.overtime.indexOf(this.props.params.babyid) == -1) {
                                if ((new Date().getTime() - new Date(res.data.endtime).getTime()) / 24 / 60 / 60 / 1000 >= -30)
                                    viewtime = 1
                            }
                        }
                    }
                    this.setState({
                        viewtime,
                        info: {
                            url: 'http://qr.liantu.com/api.php?&w=200&text=' + res.data.mdtid + '',
                            mdtid: res.data.mdtid,
                            telephone: res.data.telephone,
                            endTime: res.data.endtime,
                            userid: res.data.userid,
                            isadmin: res.data.isadmin,
                            authstatus: res.data.authstatus,
                            deviceType: res.data.deviceType,
                            babyid: res.data.babyid,
                            deviceid: res.data.deviceid
                        }
                    });
                    localStorage.deviceId=res.data.deviceid;
                    localStorage.schoolname = res.data.schoolname;
                    //缴费按钮--添加百度统计点击事件
                    // document.querySelector('.tgPayMoney').onclick = function() {
                    //     _hmt.push(['_trackEvent', 'page', 'more', '缴费']);
                    // };
                }
            })
        })
        HttpService.query({
            url: 'app/device/getDevice',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
            },
            success: (res => {
                if(res.code == "10072"){
                    this.setState({firewallSwitch:res.data.firewall});
                }
            })
        });

    }

    //基本设备提示操作
    deviceCancel() {
        this.setState({
            admin: {
                flag: true
            }
        });
        if (!this.state.info.isadmin) {
            var b = {
                tip: '解绑当前设备',
                content: '确定要解除绑定吗？'
            };
            this.config = Object.assign({}, this.config, b);
        } else {
            var a = {
                tip: '解绑当前设备',
                content: '解除管理员绑定后，其他监护成员将一同解除，且设备恢复出厂设置，只保留激活状态及设备有效期'
            };
            this.config = Object.assign({}, this.config, a);
        }
    }
    //删除设备(管理员)
    delDevice2() {
        HttpService.query({
            url: '/app/object/cancelDevice',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10112') {
                    if (localStorage.babylength == 1) {
                        localStorage.babylength = 0;
                        this.context.router.push('/addDevice');
                        return;
                    }
                    window.localStorage.delDevice = 1;
                    window.localStorage.is = '0';
                    this.context.router.push('/map/' + localStorage.appToken + '/' + localStorage.userid);
                }
            })

        });
    }

    //删除设备
    delDevice() {
        HttpService.query({
            url: '/app/object/cancelBaby',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                weixinclient: 'true'
            },

            success: (res => {
                if (res.code == '10070') {
                    if (localStorage.babylength == 1) {
                        localStorage.babylength = 0;
                        this.context.router.push('/addDevice');
                        return;
                    }
                    window.localStorage.delDevice = 1;
                    window.localStorage.is = '0';
                    this.context.router.push('/map/' + localStorage.appToken + '/' + localStorage.userid);
                }
            })
        });
    }
    deviceChange() {
        let deviceType = '智能学生证';
        if (this.state.info.deviceType == 3) {
            deviceType = '考勤卡';
        }
        this.setState({
            admin: {
                flag: true
            }
        });
        var b = {
            tip: '更换设备',
            content: '当前设备类型为' + deviceType + '，请扫描新的设备二维码或条形码，完成更换！',
            type: 'change'
        };
        this.config = Object.assign({}, this.config, b);
    }

    logOut() {
        this.context.router.push('/');
    }
    viewCode() {
        console.log('设备二维码');
        //_hmt.push(['_trackEvent', 'page', 'more', '设备二维码']);
        this.setState({viewCode: 1})
    }
    closeCode() {
        this.setState({viewCode: 0})
    }
    closeTime() {
        this.setState({viewtime: 0});
        if (localStorage.overtime == undefined)
            localStorage.overtime = ''
        localStorage.overtime = localStorage.overtime + this.props.params.babyid + ',';
    }

    /**
     * 防火墙开关
     */
    onClickSwitch(){
        this.setState({firewallSwitch:!this.state.firewallSwitch});
        HttpService.query({
            url: '/app/device/changeFirewall',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                deviceid: this.state.info.deviceid,
                firewall: !this.state.firewallSwitch,
            },
            success: (res => {
                if(res.code != 10100){
                    Toast.toast(res.msg);
                    this.setState({firewallSwitch:!this.state.firewallSwitch});
                }
            })
        });

    }

    /**
     * 不是管理员
     * @returns {XML}
     */
    isNoAdmin(){
        Toast.toast('当前功能仅限管理员使用，请联系管理员');
    }
    render() {

        const {
            info,
            admin,
            uimg,
            utel,
            viewCode,
            viewtime
        } = this.state;
        return (
            <div className="more" style={{
                background: '#eee',
                minHeight: '100%',
                paddingBottom: '4rem'
            }}>

                <Popup config={this.config} blockOrNone={admin.flag} _flag={admin.flag}/>
                <R_header_fixed left="1" title="更多"/>
                <div className="more-content">
                    <img src={info.url} style={{display:'none'}} />
                    {
                        viewCode == 1
                        ? <div id='viewCode'>
                                <div className="barcode">
                                    <img src={info.url}/>
                                    <div className="mdtid" style={{
                                        color: '#666'
                                    }}>扫描二维码关注宝贝的设备</div>
                                    <div className="mdtid">设备IMEI号:{info.mdtid}</div>
                                    <div className='closecode' onClick={this.closeCode.bind(this)}>确定</div>
                                </div>
                            </div>
                        : ''
                    }

                    <div className='moreuserinfo'>
                        <div className='imgbox'><img src={uimg}/></div>
                        <p>{utel}</p>
                    </div>
                    {info.deviceType == '2' && info.isadmin
                        ? <Link to={'/authen/' + info.telephone} authstatus={info.authstatus}>
                                <div className="shiming">
                                    <div className="img">
                                        <img src={shiming}/>
                                    </div>
                                    <div className="input">sim卡实名认证</div>
                                    <div className="select">
                                        {
                                            info.authstatus == '0'
                                            ? <div className="step">
                                                    <span style={{
                                                        color: '#999999'
                                                    }} className="step"><img src={unauthen} className="authImg"/>
                                                        未认证
                                                    </span>
                                                    <span><img src={j} className="jimg"/></span>
                                                </div>
                                            : info.authstatus == '1'
                                                ? <span style={{
                                                        color: '#f7ba00'
                                                    }}>
                                                        认证中</span>
                                                : info.authstatus == '2'
                                                    ? <div className="step">
                                                            <span className="step" style={{
                                                                color: '#ff6e6e'
                                                            }}>
                                                                认证不通过</span>
                                                            <span>
                                                                <img src={j} className="jimg"/></span>
                                                        </div>
                                                    : info.authstatus == '3'
                                                        ? <span style={{
                                                                color: '#1ec94a'
                                                            }}><img src={authen} className="authImg"/>
                                                                已认证</span>
                                                        : ''
                                        }

                                    </div>
                                </div>
                            </Link>
                        : ''
                    }
                    <Link className="endtime buydev tgMoreButtonList buydevicelink" to='/BuyDevice'>
                        <div className="img">
                            <img src={imgCard}/>
                        </div>
                        <div className="input">购买新设备</div>
                        <div className="select">
                            <span className="step"><img src={j} className="jimg"/></span>
                        </div>
                    </Link>
                    <Link className="endtime tgMoreButtonList" to='/buyOrder'>
                        <div className="img">
                            <img src={order}/>
                        </div>
                        <div className="input">购买订单</div>
                        <div className="select">
                            <span className="step"><img src={j} className="jimg"/></span>
                        </div>
                    </Link>

                    {info.deviceType == 2 && info.deviceid&&info.loststatus!=1
                        ? <Link className="tgPayMoney" to={'/pay/' + info.babyid + '/' + info.deviceid}>
                            <div className="phone">
                                <div className="img">
                                    <img src={pay}/>
                                </div>
                                <div className="input">缴费</div>
                                <div className="select" style={{
                                    color: '#00b4ed'
                                }}>
                                    <span className="step">到期日期：{info.endTime}</span>
                                    <span className="step"><img src={j} className="jimg"/></span>
                                </div>
                            </div>
                        </Link>
                        : ''
                    }
                    <div className="phone tgMoreButtonList buydev" data-tgOptValue="设备手机号">
                        <div className="img">
                            <img src={phone}/>
                        </div>
                        <div className="input">设备手机号</div>
                        <div className="select">
                            {info.deviceType == 3
                                ? '当前设备不支持'
                                : info.telephone}
                        </div>
                    </div>
                    <div className="endtime tgMoreButtonList" data-tgOptValue="设备二维码" onClick={this.viewCode.bind(this)}>
                        <div className="img">
                            <img src={scode}/>
                        </div>
                        <div className="input">设备二维码</div>
                        <div className="select">
                            <img style={{
                                width: '2rem'
                            }} src={scodeh}/>
                            <span className="step"><img src={j} className="jimg"/></span>
                        </div>
                    </div>
                    {this.state.info.deviceType==3?'':
                    <div>
                    {
                        this.state.info.isadmin==true?
                            <div>
                                <div className="endtime" onClick={this.deviceChange.bind(this)}>
                                    <div className="img">
                                        <img src={genghuan}/>
                                    </div>
                                    <div className="input">更换设备</div>
                                    <div className="select"></div>
                                </div>
                                <div className="endtime tgMoreButtonList" data-tgOptValue="防火墙">
                                    <div className="img">
                                        <img src={firewall}/>
                                    </div>
                                    <div className="input">防火墙</div>
                                    <div className={this.state.firewallSwitch==true?'widget switch checked':'widget switch '} >
                                        <div className="wrapper"></div>
                                        <div className="circle" onClick={this.onClickSwitch.bind(this)}></div>
                                    </div>
                                </div>
                                <Link to="/Disturb" className="endtime tgMoreButtonList" data-tgOptValue="勿扰模式">
                                    <div className="img">
                                        <img src={disturb}/>
                                    </div>
                                    <div className="input">勿扰模式</div>
                                </Link>
                            </div>
                            :
                            <div>
                                <div className="endtime tgMoreButtonList" data-tgOptValue="防火墙">
                                    <div className="img">
                                        <img src={firewall}/>
                                    </div>
                                    <div className="input">防火墙</div>
                                    <div className={this.state.firewallSwitch==true?'widget switch checked':'widget switch '} >
                                        <div className="wrapper"></div>
                                        <div className="circle" onClick={this.isNoAdmin.bind(this)}></div>
                                    </div>
                                </div>
                                <div to="/Disturb" onClick={this.isNoAdmin.bind(this)} className="endtime tgMoreButtonList" data-tgOptValue="勿扰模式">
                                    <div className="img">
                                        <img src={disturb}/>
                                    </div>
                                    <div className="input">勿扰模式</div>
                                </div>
                            </div>

                    }
</div>}
                    <div className="endtime tgMoreButtonList" data-tgOptValue="解绑当前设备" onClick={this.deviceCancel.bind(this)}>
                        <div className="img">
                            <img src={deletes}/>
                        </div>
                        <div className="input">解绑当前设备</div>
                        <div className="select"></div>
                    </div>

                </div>

            </div>
        )
    }

}

More.contextTypes = {
    router: React.PropTypes.object.isRequired
};
